package com.atguigu.eduservice.service.impl;

import com.atguigu.commonutils.JwtUtil;
import com.atguigu.commonutils.Result;
import com.atguigu.eduservice.client.VodClient;
import com.atguigu.eduservice.entity.EduComment;
import com.atguigu.eduservice.entity.EduCourse;
import com.atguigu.eduservice.mapper.EduCommentMapper;
import com.atguigu.eduservice.service.EduCommentService;
import com.atguigu.eduservice.service.EduCourseService;
import com.atguigu.servicebase.handler.CustomException;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 评论 服务实现类
 * </p>
 *
 * @author test.java
 * @since 2023-03-23
 */
@Service
public class EduCommentServiceImpl extends ServiceImpl<EduCommentMapper, EduComment> implements EduCommentService {

	@Resource
	private VodClient vodClient;
	@Resource
	private EduCourseService eduCourseService;

	@Override
	public Result saveEduComment(String comment, String courseId, HttpServletRequest request) {


		Result member = vodClient.getMember(request);
		if (member.getData() == null) {
			return Result.error().message("用户未登陆");
		}
		//获取请求头中的用户id
		String token = request.getHeader("token");
		//解析token
		Claims claims = null;
		try {

			claims = JwtUtil.parseJWT(token);
			String userId = claims.getSubject();
			//将评论保存到表中->要单独设置评论表的课程id和讲师id
			EduCourse course = eduCourseService.getById(courseId);
			String teacherId = course.getTeacherId();
			EduComment eduComment = new EduComment();
			eduComment.setContent(comment);
			eduComment.setMemberId(userId);
			eduComment.setTeacherId(teacherId);
			eduComment.setCourseId(courseId);
			boolean save = this.save(eduComment);
			if (!save) {
				return Result.error().message("评论失败");
			}

		} catch (Exception exception) {
			exception.printStackTrace();
			//throw new CustomException(20001, "评论失败");
			return Result.error().message("评论失败");
		}
		return Result.ok().message("评论成功");
	}
}
